<html>
<head>
    <meta charset="utf-8">
    <title>API</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../res/layui/css/layui.css" media="all">

</head>
<style>
    .result {
        display: none;
    }
    .deviation {
        width: 150px;
        margin-left: -75px;
    }
    .layui-form-item {
        margin-top: 30px;
    }
</style>
<body>

<div class="layui-fluid">
    <div class="layui-card ">
        <div class="layui-card-body layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label deviation">上次搜索结果</label>
                <div class="layui-input-block">
                    <button class="layui-btn layui-btn-sm" id="upload">导入Excel</button>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label deviation">第几页</label>
                <div class="layui-input-block">
                    <input type="number" name="page" lay-verify="required" placeholder="第几页" class="layui-input" value="1"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label deviation">页大小</label>
                <div class="layui-input-block">
                    <input type="number" name="per_page" lay-verify="required" placeholder="页大小" class="layui-input" value="30"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label deviation">关键字</label>
                <div class="layui-input-block">
                    <input type="text" name="keyword" lay-verify="required" placeholder="关键字" class="layui-input"/>
                </div>
            </div>
            <input type="button" class="layui-btn" style="width: 100%"  id="goSearch" value="搜索">
            <div class="layui-form-item">
                <label class="layui-form-label deviation">搜索结果</label>
                <div class="layui-input-block">
                    <button class="layui-btn layui-btn-sm result" id="export">下载Excel</button>
                </div>
            </div>
        </div>

    </div>
</div>

<script type="text/html" id="LAY-excel-export-ans">
    {{# layui.each(d.data, function(file_index, item){ }}
    <blockquote class="layui-elem-quote">{{d.files[file_index].name}}</blockquote>
    <div class="layui-tab">
        <ul class="layui-tab-title">
            {{# layui.each(item, function(sheet_name, content) { }}
            <li>{{sheet_name}}</li>
            {{# }); }}
        </ul>
        <div class="layui-tab-content">
            {{# layui.each(item, function(sheet_name, content) { }}
            <div class="layui-tab-item">
                <table class="layui-table">
                    {{# layui.each(content, function(row_index, value) { }}
                    {{# var col_index = 0 }}
                    <tr>
                        {{# layui.each(value, function(col_key, val) { }}
                        <td id="table-export-{{file_index}}-{{sheet_name}}-{{row_index}}-{{col_index++}}">{{val}}</td>
                        {{# });}}
                    </tr>
                    {{# });}}
                </table>
                <!--<pre class="layui-code">{{JSON.stringify(content, null, 2)}}</pre>-->
            </div>
            {{# }); }}
        </div>
    </div>
    {{# }) }}
</script>


<script type="text/javascript" src="../res/layui/layui.js"></script>
<script>
    layui.config({
        base: '../res/static/js/util/' //你存放新模块的目录，注意，不是layui的模块目录
    }).use(['jquery', 'layer','upload','excel','laytpl','element'], function () {
        let $ = layui.$
            , layer = layui.layer
            , upload = layui.upload
            , excel = layui.excel
            , laytpl = layui.laytpl
            , element = layui.element

        //搜索地址
        let searchUrl = 'https://api.github.com/search/repositories';

        //搜索参数
        let searchparameters = {
            //关键字
            q: null,
            //排序方式 stars,forks,updated 默认是最佳匹配
            //sort: null,
            //asc：升序,desc：降序。默认为desc。
            //order: null
        }

        let dataMap = {
        };

        $("#goSearch").on("click",function () {
            searchparameters.q = $('input[name="keyword"]').val()
            searchparameters.per_page = $('input[name="per_page"]').val()
            searchparameters.page = $('input[name="page"]').val()
            if(!searchparameters.q){
                layer.msg('请填写关键字');
                return ;
            }
            if(!searchparameters.per_page){
                layer.msg('请填写页大小');
                return ;
            }
            if(!searchparameters.page){
                layer.msg('请填写第几页');
                return ;
            }
            layer.load(1);
            $.ajax({
                xhrFields: {
                    withCredentials: true
                },
                type: "GET",
                url: searchUrl +"?q="+searchparameters.q+"&per_page="+searchparameters.per_page+"&page="+searchparameters.page,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Accept","application/vnd.github.v3+json");
                },
            }).done(function (res) {
                if(res.items.length > 0){
                    layui.each(res.items, function(file_index, item){
                        if(dataMap[item.id] !=null){
                            item.addstar = item.stargazers_count - dataMap[item.id].stargazers_count
                        }else {
                            item.addstar = item.stargazers_count
                        }
                        dataMap[item.id]=item;
                    })
                }
                layer.closeAll('loading');
                layer.msg("操作成功", {icon: 1});
                $("#export").show();
            })
        })


        $("#export").on("click",function () {
            let dataList = new Array();
            layui.each(dataMap, function(key, value){
                dataList.push(value);
            })
            dataList.unshift(
                {"id":"id", "name":"name", 'stargazers_count':"stargazers_count", 'addstar':"addstar" }
            )
            excel.exportExcel({
                'dataList': dataList,
            }, '导出数据.xlsx', 'xlsx')
            dataMap = {};
            $("#export").hide();
            layer.msg("导出成功,记录已清空", {icon: 1});
        })


        var uploadInst = upload.render({
            elem: '#upload' //绑定元素
            , url: './demo.js'
            , auto: false //选择文件后不自动上传
            , accept: 'file'
            , choose: function (obj) {// 选择文件回调
                var files = obj.pushFile()
                var fileArr = Object.values(files)// 注意这里的数据需要是数组，所以需要转换一下
                // 用完就清理掉，避免多次选中相同文件时出现问题
                for (var index in files) {
                    if (files.hasOwnProperty(index)) {
                        delete files[index]
                    }
                }
                $('#LAY-excel-upload').next().val('');
                uploadExcel(fileArr) // 如果只需要最新选择的文件，可以这样写： uploadExcel([files.pop()])
            }
        });


        /**
         * 上传excel的处理函数，传入文件对象数组
         * @param  {FileList} files [description]
         * @return {[type]}       [description]
         */
        function uploadExcel(files) {
            try {
                excel.importExcel(files, {}, function (data, book) {
                    //处理数据
                    for (var sheet in data[0]) {//格式化数据
                        var menuMap=data[0][sheet][0]
                        for (var item in data[0][sheet]) {
                            if(item == '0'){
                                continue;
                            }
                            for (var cell in data[0][sheet][item]) {
                                if(menuMap[cell]===''){
                                    delete data[0][sheet][item][cell];
                                    continue;
                                }
                                data[0][sheet][item][menuMap[cell]]=data[0][sheet][item][cell]
                                delete data[0][sheet][item][cell];
                            }
                        }
                    }
                    importData=data[0]
                    layer.open({
                        title: '文件转换结果'
                        , area: ['80%', '80%']
                        , tipsMore: true
                        , btn: ['确认导入']
                        , content: laytpl($('#LAY-excel-export-ans').html()).render({data: data, files: files})
                        , success: function () {
                            layer.closeAll('loading');
                            element.render('tab')
                            // 处理合并
                            for (var file_index in book) {
                                if (!book.hasOwnProperty(file_index)) {
                                    continue
                                }
                                // 遍历每个Sheet
                                for (var sheet_name in book[file_index].Sheets) {
                                    if (!book[file_index].Sheets.hasOwnProperty(sheet_name)) {
                                        continue
                                    }
                                    var sheetObj = book[file_index].Sheets[sheet_name]
                                    // 仅在有合并参数时进行操作
                                    if (!sheetObj['!merges']) {
                                        continue
                                    }
                                    // 遍历每个Sheet中每个 !merges
                                    for (var merge_index = 0; merge_index < sheetObj['!merges'].length; merge_index++) {
                                        var mergeObj = sheetObj['!merges'][merge_index]
                                        // 每个合并参数的 s.c 表示左上角单元格的列，s.r 表示左上角单元格的行，e.c 表示右下角单元格的列，e.r 表示右下角单元格的行，计算时注意 + 1
                                        $('#table-export-' + file_index + '-' + sheet_name + '-' + mergeObj.s.r + '-' + mergeObj.s.c)
                                            .prop('rowspan', mergeObj.e.r - mergeObj.s.r + 1)
                                            .prop('colspan', mergeObj.e.c - mergeObj.s.c + 1)
                                        for (var r = mergeObj.s.r; r <= mergeObj.e.r; r++) {
                                            for (var c = mergeObj.s.c; c <= mergeObj.e.c; c++) {
                                                // 排除左上角
                                                if (r === mergeObj.s.r && c === mergeObj.s.c) {
                                                    continue
                                                }
                                                $('#table-export-' + file_index + '-' + sheet_name + '-' + r + '-' + c).remove()
                                            }
                                        }
                                    }
                                }
                            }
                        } , yes: function (index, layero) {
                            if(importData){
                                layer.load(1);
                                importData.dataList.shift()
                                layui.each(importData.dataList, function(file_index, item){
                                    item.addstar = item.stargazers_count
                                    dataMap[item.id]=item;
                                });
                                layer.closeAll('loading');
                                console.log(dataMap);
                                layer.msg("操作成功", {icon: 1});
                            }else {
                                layer.msg('请等待数据渲染完成');
                            }
                        }
                    })
                })
            } catch (e) {
                layer.alert(e.message)
            }
        }

    });
</script>
</body>
</html>
